package com.itheima.filter;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.filter
 */
//@WebFilter(urlPatterns = "/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1. 获取请求url
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        //2. 判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if(url.endsWith("/login")){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //3. 获取请求头中的令牌（token）
        String token = request.getHeader("Token");
        //4. 判断令牌是否存在，如果不存在，响应 401
        if(!StringUtils.hasLength(token)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value()); // 未认证，没登录，前端会自动跳转到登录页面
            return;
        }
        //5. 解析token，如果解析失败，响应 401
        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.error("解析token失败.",e);
            response.setStatus(401); // 未认证，没登录，前端会自动跳转到登录页面
            return;
        }
        //6. 放行
        filterChain.doFilter(servletRequest, servletResponse);
        //放行后
        System.out.println("放行后.......");
    }
}
